package com.tzpay.tzpay.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.tzpay.tzpay.R;
import com.tzpay.tzpay.ui.BaseActivity;
import com.tzpay.tzpay.utils.Utils;


public class WebActivity extends BaseActivity {

    public static final String TAG = WebActivity.class.getSimpleName();

    private WebView webView;
    private String currentUrl;
    private ProgressBar progressBar;
    //下拉刷新
    private SwipeRefreshLayout swipeRefreshLayout;
    private SwipeRefreshLayout emptyRefreshLayout;

    public static Intent getIntent(Activity activity, String url, String headerTitle) {
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("webURL", url);
        intent.putExtra("title", headerTitle);
        return intent;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.primary);
        emptyRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.empty_refresh_layout);
        emptyRefreshLayout.setColorSchemeResources(R.color.primary, R.color.primary);

        progressBar = (ProgressBar) findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        webView = (WebView) findViewById(R.id.webView);
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        setDefaultClient();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webView.getSettings().setAllowFileAccessFromFileURLs(true);
            webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");
        //启用地理定位
        settings.setGeolocationEnabled(true);
        //开启DomStorage缓存
        settings.setDomStorageEnabled(true);
        settings.setGeolocationDatabasePath(getFilesDir().getPath());
        //启用数据库
        settings.setDatabaseEnabled(true);
        dealUrl(getIntent());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取历史列表
                WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
                WebHistoryItem webHistoryItem = mWebBackForwardList.getCurrentItem();
                if (null != webHistoryItem) {
                    String url = webHistoryItem.getUrl();
                    WebActivity.this.loadWebView(webView, url);
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        emptyRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取历史列表
                WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
                WebHistoryItem webHistoryItem = mWebBackForwardList.getCurrentItem();
                if (null != webHistoryItem) {
                    String url = webHistoryItem.getUrl();
                    WebActivity.this.loadWebView(webView, url);
                } else {
                    WebActivity.this.loadWebView(webView, currentUrl);
                }
                emptyRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void setupContentView() {
        setContentView(R.layout.activity_web);
    }

    private void dealUrl(Intent intent) {
        currentUrl = intent.getStringExtra("webURL");
        String title = intent.getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = getString(R.string.app_name);
        }
        changeTitle(title);
        if (TextUtils.isEmpty(currentUrl)) {
            finish();
        }

        loadWebView(webView, currentUrl);
    }

    /**
     * 设置默认的client
     */
    private void setDefaultClient() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress >= 50) {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title)) {
                    changeTitle(title);
                } else {
                    changeTitle(getString(R.string.app_name));
                }
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                // 请求定位信息
                final boolean remember = false;
                callback.invoke(origin, true, remember);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }
        });
        WebViewClient webViewClient = new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                currentUrl = url;
                loadWebView(view, url);
                return true;
            }

            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
            }

            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                progressBar.setVisibility(View.GONE);
            }
        };
        webView.setWebViewClient(webViewClient);
    }

    /**
     * 加载url
     */
    private void loadWebView(WebView webView, String url) {
        if (!Utils.isCanConnectionNetWork(WebActivity.this)) {
            swipeRefreshLayout.setVisibility(View.GONE);
            emptyRefreshLayout.setVisibility(View.VISIBLE);
            return;
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            emptyRefreshLayout.setVisibility(View.GONE);

        }
        setCookie();
        webView.loadUrl(url);
    }

    /**
     * 返回键的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handleBackReturnEvent();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handleBackReturnEvent() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }


    }

    private void returnToMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }


    /**
     * 设置Cookie
     */
    private void setCookie() {
//        CookieSyncManager.createInstance(WebActivity.this);
//        CookieManager cookieManager = CookieManager.getInstance();
//        CookieSyncManager.getInstance().startSync();
//        CookieManager.allowFileSchemeCookies();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            cookieManager.setAcceptThirdPartyCookies(webView, true);
//        }
//        cookieManager.setAcceptCookie(true);
//        webView.clearCache(true);
//        webView.clearHistory();
//        cookieManager.setCookie(domainName, "sessionid=" + sessionId);
//        cookieManager.setCookie(domainName, "qf_uid=" + qfUid);
//
//        CookieSyncManager.getInstance().sync();
    }


    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        dealUrl(intent);
    }

}

